package javaClassExercise.designPatterns.prototypeModel;

import java.io.*;

/**
 * Created by lomo.
 *
 * 浅复制: 将一个对象复制后，基本数据类型的变量都会重新创建，而引用类型，指向的还是原对象所指向的
 *
 * 深复制: 将一个对象复制后，不论是基本数据类型还有引用类型，**都是重新创建**的。
 *
 * 简单地: 就是深复制进行了完全彻底的复制，而浅复制不彻底.
 *
 */
public class prototypeT implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;
    private String string;

    private SerializableObject obj;

    //潜复制
    public Object clone() throws CloneNotSupportedException {
        Prototype prototype = (Prototype) super.clone();
        return prototype;
    }

    //深复制
    //深复制，需要采用流的形式读入当前对象的二进制输入，再写出二进制数据对应的对象
    public Object deepClone() throws IOException, ClassNotFoundException {
         /* 写入当前对象的二进制流 */
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(this);

        /* 读出二进制流产生的新对象 */
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return objectInputStream.readObject();
    }

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }

    public SerializableObject getObj() {
        return obj;
    }

    public void setObj() {
        this.obj = obj;
    }

}

class SerializableObject implements Serializable {
    private static final long serialVersionUID = 1L;
}